package deepbrain.simnetwork.loader.xml;

import java.io.FileInputStream;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import deepbrain.simnetwork.exception.SimNetworkException;
import deepbrain.simnetwork.factory.XmlNetworkStateFactory;
import deepbrain.simnetwork.loader.ConnectionsLoader;
import deepbrain.simnetwork.loader.NetworkLoaderImpl;
import deepbrain.simnetwork.mechanism.Mechanism;
import deepbrain.simnetwork.network.Network;

public class XmlNetworkLoader extends NetworkLoaderImpl {

	protected String name;
	protected String mechanismClass;

	public XmlNetworkLoader(String xmlPath) throws SimNetworkException {
		this.setNodesFactory(new XmlNetworkStateFactory(xmlPath));
		Document document = null;
		SAXReader reader = new SAXReader();
		try {
			document = reader.read(new FileInputStream(xmlPath));
		} catch (Exception e) {
			throw new SimNetworkException(e);
		}

		numOfNodes = Integer.parseInt(((Element) document
				.selectSingleNode("//network")).elementTextTrim("nodenum"));
		name = ((Element) document.selectSingleNode("//network"))
				.elementTextTrim("name");
		mechanismClass = ((Element) document.selectSingleNode("//network"))
				.elementTextTrim("network-mechanism");

		String strConnectionsLoader = ((Element) document
				.selectSingleNode("//network"))
				.elementTextTrim("connections-loader");
		ConnectionsLoader connectionsLoader = null;
		try {
			connectionsLoader = (ConnectionsLoader) Class.forName(
					strConnectionsLoader).getConstructor(
					new Class<?>[] { String.class }).newInstance(xmlPath);
		} catch (Exception e) {
			throw new SimNetworkException(e);
		}
		setConnectionsLoader(connectionsLoader);
	}

	@Override
	public Network loadNetwork() throws SimNetworkException {
		Network network = super.loadNetwork();
		if (name != null && name.length() != 0)
			network.setName(name);
		if (mechanismClass != null && mechanismClass.length() != 0) {
			try {
				Mechanism mechanism = (Mechanism) Class.forName(mechanismClass)
						.newInstance();
				network.setMechanism(mechanism);
			} catch (Exception e) {
				throw new SimNetworkException(e);
			}
		}
		return network;
	}
}
